package de.tabuma.lib.cm.crud;

import de.tabuma.lib.contentmanagement.*;
import de.tabuma.lib.cm.crud.*;
import de.tabuma.lib.contentmanagement.entity.Content;
import de.tabuma.lib.contentmanagement.entity.ValidationException;
import java.util.*;
import javax.servlet.http.*;
import java.util.regex.*;

/**
 *
 * @author alefen
 */
public class RemoveControllerFacade {
    public static void controller(Content content, HttpServletRequest request) {
        
        if(request.getParameter(constants.CANCEL)!=null) {
            ListControllerFacade.controller(content, request);
            return;
        }

        String id = request.getParameter(content.GeneralContent.getParamName()+constants.id);
        int idInt = Integer.valueOf(id).intValue();

        if(request.getParameter(constants.REMOVE1)!=null) {
            try {
                content.FormContent.getFacadeObject().removeElement(idInt, content.GeneralContent.getUser());
                String message = constants.getValueFromProperties(constants.MESSAGE_INFO_REMOVE, request.getLocale());
                String p = Pattern.quote("{1}");
                message = message.replaceAll(p,content.FormContent.getEntityName());
                request.setAttribute(constants.MESSAGE_INFO,message);
            }
            catch(ValidationException e) {
                String message = constants.getValueFromProperties(constants.MESSAGE_ERROR_REMOVE, request.getLocale());
                String p = Pattern.quote("{1}");
                message = message.replaceAll(p,content.FormContent.getEntityName()) + " " + e.getLocalizedMessage();
                request.setAttribute(constants.MESSAGE_ERROR,message);

            }
            ListControllerFacade.controller(content, request);
            return;
        }

        request.setAttribute(constants.OBJECT, content.FormContent.getFacadeObject().getElement(idInt));
        request.setAttribute(content.GeneralContent.getParamName()+constants.id,idInt);
        request.setAttribute(content.GeneralContent.getParamName(),constants.REMOVE);

    }
}
